﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AtletIS.Shared.Data.aDbDataSetTableAdapters;
using System.Threading;
using AtletIS.Shared.Helpers;

namespace AtletIS.Shared.Forms
{
    public partial class frmBoardControl : Form
    {
        const string sOrderByDesc = "ChipDateTime DESC, DataIndex";
        private string sPcId = string.Empty, sDataIndex = string.Empty;

        // Constructor
        public frmBoardControl()
        {
            InitializeComponent();
            this.Icon = Properties.Resources.AtletIS64;
        }

        // Form Load
        private void frmBoardControl_Load(object sender, EventArgs e)
        {
            this.gbAuto.Enabled = true;
            this.tsmiAuto.Checked = true;
            this.gbManual.Enabled = false;
            this.tsmiManual.Checked = false;

            this.btnAutoStart.Enabled = true;
            this.btnAutoStop.Enabled = false;

            Globals.ActiveCompetition = CompetitionHelper.ConvertToEntity(DatabaseHelper.GetCompetitionsActive().Rows[0]);

            this.lbBoard.Items.Clear();

            Helpers.TextScoreBoardHelper.Init(Properties.Settings.Default.BoardPort);
            if (Helpers.TextScoreBoardHelper.bConnected)
            {
                this.tsslConnected.Text = "Tabuľa: ONLINE";
            }
            else
            {
                this.tsslConnected.Text = "Tabuľa: OFFLINE";
            }
        }

        // Close
        private void tsbClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        // Form Closing
        private void frmBoardControl_FormClosing(object sender, FormClosingEventArgs e)
        {
            Application.Exit();
        }
        
        // Automatic click
        private void tsmiAuto_Click(object sender, EventArgs e)
        {
            gbAuto.Enabled = true;
            tsmiAuto.Checked = true;
            gbManual.Enabled = false;
            tsmiManual.Checked = false;
        }

        // Manual click
        private void tsmiManual_Click(object sender, EventArgs e)
        {
            gbAuto.Enabled = false;
            tsmiAuto.Checked = false;
            gbManual.Enabled = true;
            tsmiManual.Checked = true;
        }

        // Auto START
        private void btnAutoStart_Click(object sender, EventArgs e)
        {
            this.btnAutoStart.Enabled = false;
            this.btnAutoStop.Enabled = true;
            this.tmrRefresh.Enabled = true;
        }

        // Auto STOP
        private void btnAutoStop_Click(object sender, EventArgs e)
        {
            this.btnAutoStart.Enabled = true;
            this.btnAutoStop.Enabled = false;
            this.tmrRefresh.Enabled = false;

            this.sPcId = string.Empty;
            this.sDataIndex = string.Empty;

            this.lbBoard.Items.Clear();
        }

        // Auto REFRESH
        private void tmrRefresh_Tick(object sender, EventArgs e)
        {
            this.RefreshBoard();
        }

        // Refresh
        private void RefreshBoard()
        {
            try
            {
                DataTable dtChipData = DatabaseHelper.GetChipDataBoardData(Globals.ActiveCompetition.ID); 

                if (dtChipData.Rows.Count > 0)
                {
                    int nCount = 0;
                    foreach (DataRow dr in dtChipData.Select(null, sOrderByDesc))
                    {
                        if (nCount >= 4)
                            break;

                        if (nCount == 0)
                        {
                            // Ak je záznam rovnaký ako pri predošlom cykle, tak nič
                            if (dr["DataIndex"].ToString() == this.sDataIndex & dr["PcId"].ToString() == this.sPcId)
                                break;

                            this.lbBoard.Items.Clear();
                            this.sPcId = dr["PcId"].ToString();
                            this.sDataIndex = dr["DataIndex"].ToString();
                        }

                        this.PrintRow(dr, nCount);
                        nCount += 1;
                    }

                    this.tsslRefresh.Text = "Obnovené: " + DateTime.Now.ToLongTimeString();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace, "Board Control", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.tmrRefresh.Enabled = false;
            }
        }

        private void PrintRow(DataRow dr, int index)
        {
            string sLine = string.Empty;
            TimeSpan tsResult;

            DateTime dtChipDateTime = Convert.ToDateTime(dr["ChipDateTime"]);

            if (dtChipDateTime.Millisecond > 0)
                tsResult = new TimeSpan(dtChipDateTime.Hour, dtChipDateTime.Minute, dtChipDateTime.Second + 1);
            else
                tsResult = new TimeSpan(dtChipDateTime.Hour, dtChipDateTime.Minute, dtChipDateTime.Second);

            // Write to ListBox
            sLine = "[" + dr["DataIndex"].ToString().PadLeft(4, '0') + "]  (";
            sLine += dr["StartNumber"].ToString().PadLeft(3, '0') + ")  ";
            sLine += dr["Surname"].ToString().PadRight(22, ' ') + "  ";
            sLine += dr["BoardName"].ToString().PadLeft(3, '0') + "  ";
            sLine += string.Format("{0:0}:{1:00}:{2:00}", tsResult.Hours, tsResult.Minutes, tsResult.Seconds);
            this.lbBoard.Items.Add(sLine);

            // Write to Board (adress: 111, 112, 113, 114)
            if (index != 0)
            {
                Thread.Sleep(350);
            }

            byte adress = Convert.ToByte(111 + index);
            Helpers.TextScoreBoardHelper.ClearLine(adress);
            Helpers.TextScoreBoardHelper.WriteResult(
                Convert.ToInt32(dr["StartNumber"]),
                dr["Surname"].ToString(),
                dr["BoardName"].ToString(),
                tsResult,
                adress);
        }

        #region Manual

        // Manual clear
        private void btnManualClear_Click(object sender, EventArgs e)
        {
            byte adress = 111;

            if (chkAll.Checked)
            {
                for (int i = 1; i <= 4; i++)
                {
                    adress = Convert.ToByte(i + 110);
                    Helpers.TextScoreBoardHelper.ClearLine(adress);
                }
            }
            else
            {
                adress = Convert.ToByte(Convert.ToInt32(nudLine.Value) + 110);
                Helpers.TextScoreBoardHelper.ClearLine(adress);
            }
        }

        // Manual write
        private void btnManualText_Click(object sender, EventArgs e)
        {
            byte adress = Convert.ToByte(Convert.ToInt32(nudLine.Value) + 110);
            Helpers.TextScoreBoardHelper.WriteSimpleText(txtManual.Text, adress);
        }

        #endregion

        







    }
}
